#include <logbase.h>
#include <stdarg.h>
#include <fcntl.h> // file option
#include <errno.h>
#include <cplTime.h>

typedef struct
{
    int id;
    int val;
    char buf[8];
} myDataInfStc;

#define MY_TEST_DATA_MAX_LEN 10
#define MY_TEST_ID_MAX_VAL (MY_TEST_DATA_MAX_LEN / 3)

myDataInfStc *mybuf[MY_TEST_DATA_MAX_LEN];
int mySortCbk(const void *a, const void *b)
{
    myDataInfStc **tmpa = (myDataInfStc **)a;
    myDataInfStc **tmpb = (myDataInfStc **)b;
    if(!(tmpa && *tmpa && tmpb && *tmpb))
    {
        logerrorc("");
        return -1;
    }
    return (**tmpa).id - (**tmpb).id;
}
int main(int argc, char **argv)
{
    srand(time(NULL));
    for (int i = 0; i < MY_TEST_DATA_MAX_LEN; i++)
    {
        myDataInfStc *tmpdt = (myDataInfStc *)malloc(sizeof(myDataInfStc));
        tmpdt->id = rand() % MY_TEST_ID_MAX_VAL;
        tmpdt->val = i;
        mybuf[i] = tmpdt;
    }
    for (int i = 0; i < MY_TEST_DATA_MAX_LEN; i++)
    {
        logdebugc("org data[%d]:%d,%d", i, mybuf[i]->id, mybuf[i]->val);
    }
    qsort(mybuf, MY_TEST_DATA_MAX_LEN, sizeof(mybuf[0]), mySortCbk);
    for (int i = 0; i < MY_TEST_DATA_MAX_LEN; i++)
    {
        logdebugc("sort data[%d]:%d,%d", i, mybuf[i]->id, mybuf[i]->val);
    }
    for (int i = 0; i < MY_TEST_DATA_MAX_LEN; i++)
    {
        mybuf[i]->val = i;
    }
    for (int i = 0; i < MY_TEST_DATA_MAX_LEN; i++)
    {
        logdebugc("resort data[%d]:%d,%d", i, mybuf[i]->id, mybuf[i]->val);
    }
    for (int i = 0; i < MY_TEST_ID_MAX_VAL; i++)
    {
        myDataInfStc tmpFdVal[1];
        tmpFdVal[0].id = i;
        myDataInfStc *tmpFdPtr = tmpFdVal;//=====================why?
        myDataInfStc **tmpShVal = (myDataInfStc **)bsearch(&tmpFdPtr, mybuf, MY_TEST_DATA_MAX_LEN, sizeof(mybuf[0]), mySortCbk);
        if(tmpShVal)
        {
            logdebugc("fd data[%d]:%d,%d", i, (*tmpShVal)->id, (*tmpShVal)->val);
        }
        else
        {
            logerrorc("");
        }
    }
    for (int i = 0; i < MY_TEST_ID_MAX_VAL; i++)
    {
        free(mybuf[i]);
    }
    return 1;
}
